<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/8
 * Time: 20:13
 */

namespace app\base\controller;

use app\base\controller\Common;
use app\base\model;
use think\facade\Request;
use MvcBuilder\MvcBuilderHelper;
use CMaker\Maker;

/**
 * 自定义表单
 */
class CustomForm extends Common
{


    /**
     * 查看
     */
    public function index(){

        if(Request::isGet()){

            return $this->fetch();
        }

        if(Request::isPost()){
            $post = input('post.');
            $post['page'] = (isset($post['page'])) ? $post['page'] : 1;
            $post['limit'] = (isset($post['limit'])) ? $post['limit'] : 10;

            $where = '';
            if(isset($post['where']))$where = _parseWhere($post['where']);

            $model = new model\CustomForm();

            $res = $model->where($where)->page($post['page'] ,$post['limit'])->order('listorder desc')->select()->toArray();
            //当前分页没有数据，但总数还是有的
            //fixed 第二页数据删除完了之后 layuitable reload 不会自动跳转到 第一页
            if(!count($res) && $model->count($model->getPk()) > 0){
                $currpage = (($post['page'] - 1) >= 1) ? $post['page'] - 1 : 1 ;
                $res = $model->page($currpage ,$post['limit'])->select()->toArray();
            }
            $return['data'] = $res;
            $return['count'] = $model->where($where)->count();
            $return['code'] = 0;

            return json($return);

        }


    }
    /**
     * 添加
     */
    public function add(){
        return $this->fetch();
    }
    /**
     * 保存添加
     */
    public function add_action(){
        $post = input('post.');
        foreach($post['component_name'] as $k => $v){
            if(!isset($post['setting'][$k]) ){
                $this->error('请先编辑第'.$k.'个组件');
            }
        }
        $model = new model\CustomForm();
        $flag = $model->_save($post);
        $flag ? $this->success('操作成功'):$this->error('操作失败');

    }
    /**
     * 编辑
     */
    public function edit(){
        $id = intval(input('param.id'));
        if(!$id) $this->error('id 不存在');

        $model = new model\CustomForm();

        $data = $model->_find($id);

        $componet = '';
        foreach($data as $k => $v){
            $set = json_decode($v['setting'] ,true);
            //根据组件的设置组装组件
            $obj = Maker::build($v['component_name']);
            foreach($set['base'] as $sk => $sv){
                $obj->$sk($sv);
            }
            $componet .= $obj->render();
            $componet .= '<div class="layui-input-inline" style="display: none"><a style="float:right" href="javascript:;" onclick="showsetting(this)" class="layui-btn"><i class="fa fa-edit"></i>编辑</a></div>';
            $componet .= '<div class="hidden_list" style="display: none">';
            $componet .= Maker::build('hidden')->classname('__component_id')->name('component_id['.$k.']')->value($v['id'])->render();
            $componet .= Maker::build('hidden')->classname('__form_order')->name('form_order['.$k.']')->value($k)->render();
            $componet .= Maker::build('hidden')->classname('__component_name')->name('component_name['.$k.']')->value($v['component_name'])->render();
            //生成唯一值
            $setting_key = md5( uniqid('',true).uniqid('',true) );
            cache($setting_key ,$v['setting'],86400);
            $componet .= Maker::build('hidden')->classname('__setting')->name('setting['.$k.']')->value($setting_key)->render();
            $componet .= '</div>';

        }


        $this->assign('vo',$data);
        $this->assign('component',$componet);
        return $this->fetch();
    }

    /**
     * 保存编辑
     */
    public function edit_action(){
        $post = input('post.');
        $model = new model\CustomForm();

        foreach($post['component_name'] as $k => $v){
            if(!isset($post['setting'][$k]) ){
                $this->error('请先编辑第'.$k.'个组件');
            }
        }


        $flag = $model->_edit($post);
        $flag ? $this->success('操作成功'):$this->error('操作失败');

    }
    /**
     * 表格编辑
     */
    public function table_edit(){
        $post = input('post.');
        if(!isset($post['id']) || !$post['id'])$this->error('缺少 id');

        $model = new model\CustomForm();
        $flag = $model->isUpdate(true)->save($post);
        $flag ? $this->success('操作成功'):$this->error('操作失败');

    }
    /**
     * 删除
     */
    public function del(){
        $post = input('post.');
        $model = new model\CustomForm();
        $flag = $model->_del($post['id']);
        $flag ? $this->success('操作成功'):$this->error('操作失败');
    }

    /**
     * 批量删除
     */
    public function pdel(){
        $post = input('post.');
        $model = new model\CustomForm();
        if(!isset($post['ids']))$this->error('请选选择');
        $flag = $model->_del($post['ids']);
        $flag ? $this->success('操作成功'):$this->error('操作失败');
    }

    /**
     * 编辑组件
     */
    public function form_setting(){
        $param = input('param.');

        //获取组件保存编辑之后的setting的值,如果有值的话 再次点击编辑 则默认 用setting创建组件
        $setting = (isset($param['setting']) ) ? $param['setting'] : false;

        $MvcBuilderHelper = new MvcBuilderHelper(trim($param['component_name']) ,$setting);

        //检查编辑的组件 是否允许 在 MvcBuilder 中使用
        if(!$MvcBuilderHelper->check_allowed_component(trim($param['component_name'])))throw new \ErrorException('该组件不允许在MvcBuilder中使用');
        //获取组件的设置选项
        $setting_dom = $MvcBuilderHelper->set;


        //设置项 提交的地址
        $setting_dom['url'] = url('custom_form/save_form_setting',['form_order' => trim($param['form_order']) ,'form_type' => trim($param['component_name']) ]);


        $setting = json_decode(cache($setting) , true);


        $this->assign('action_name' ,(isset($setting['action_name']) && $setting['action_name']) ? $setting['action_name'] : '');

        //设置的dom
        $this->assign('setting' ,$setting_dom);
        return $this->fetch();
    }

    /**
     * 保存组件编辑
     */
    public function save_form_setting(){
        $post = input('post.');
        $get = input('param.');

        $el_index = $get['form_order'];

        $data['form_order'] = $el_index;
        //如果已经存在的setting_key 的 缓存标志的话，直接赋值 ，不在重新生成
        if(isset($post['setting_key']) && is_array(json_decode(cache($post['setting_key']) , true))){
            $setting_key = $post['setting_key'];
        }else{
            $setting_key = md5( uniqid('',true).uniqid('',true) );
        }
        //缓存设置的信息 86400秒 / 24个小时
        cache($setting_key ,json_encode($post) ,86400);
        //组件的设置json格式
        $data['html'] = Maker::build('hidden')->classname('__setting')->name('setting['.$el_index.']')->value($setting_key)->render();

        $value = isset($post['value']) ? explode('|',$post['value']): '';
        //获取组件
        $component = Maker::getClass($get['form_type']);

        //获取组件属性
        $component_attr = $component::attr();

        try{

            //根据post 数据 和 组件的属性 创建新的组件
            $new_component = Maker::build($get['form_type']);
            //根据post 值 与 组建的 attr 设置值
            foreach($post['base'] as $k => $v){

                if(key_exists($k,$component_attr)){
                    $new_component->$k($v);
                }
            }
            $data['new_component'] = $new_component->render();
            //获取最后一个组件的设置选项（第0个是hidden组件）
            $data['new_component_attr'] = Maker::$components[count(Maker::$components)-1];

            $this->success('编辑成功' ,'',$data);

        }catch (Exception $e){

            $this->error($e->getMessage());
        }


    }

}